package com.example.waterdispenserm2.mo.ttl.d;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.waterdispenserm2.R;
import com.example.waterdispenserm2.base.BasicsActivity;
import com.example.waterdispenserm2.databinding.ActivityCookerSlaveBinding;

//dTTL从机通信
public class CookerSlaveActivity extends BasicsActivity<ActivityCookerSlaveBinding> {
    // 业务变量
    private SerialPortManager serialManager;
    private Handler mainHandler = new Handler(Looper.getMainLooper());
    private byte currentFunction = TTLInductionCookerProtocolUtil.FUNCTION_NONE;
    private byte currentFire = TTLInductionCookerProtocolUtil.FUNCTION_NONE;
    private int currentPower = 5; // 初始功率5档
    private boolean isRunning = false; // 运行状态
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void widgetClick(View v) {
        int id = v.getId();

        // 烹饪功能选择
        if (id == R.id.btn_cook) {
            currentFunction = TTLInductionCookerProtocolUtil.FUNCTION_COOK;
            binding.tvCurrentFunction.setText("当前功能: 炒菜");
            sendFunctionCommand(TTLInductionCookerProtocolUtil.FUNCTION_COOK);
        } else if (id == R.id.btn_soup) {
            currentFunction = TTLInductionCookerProtocolUtil.FUNCTION_SOUP;
            binding.tvCurrentFunction.setText("当前功能: 煲汤");
            sendFunctionCommand(TTLInductionCookerProtocolUtil.FUNCTION_SOUP);
        } else if (id == R.id.btn_hotpot) {
            currentFunction = TTLInductionCookerProtocolUtil.FUNCTION_HOTPOT;
            binding. tvCurrentFunction.setText("当前功能: 火锅");
            sendFunctionCommand(TTLInductionCookerProtocolUtil.FUNCTION_HOTPOT);
        } else if (id == R.id.btn_porridge) {
            currentFunction = TTLInductionCookerProtocolUtil.FUNCTION_PORRIDGE;
            binding.tvCurrentFunction.setText("当前功能: 煲粥");
            sendFunctionCommand(TTLInductionCookerProtocolUtil.FUNCTION_PORRIDGE);
        } else if (id == R.id.btn_boil) {
            currentFunction = TTLInductionCookerProtocolUtil.FUNCTION_BOIL;
            binding.tvCurrentFunction.setText("当前功能: 烧水");
            sendFunctionCommand(TTLInductionCookerProtocolUtil.FUNCTION_BOIL);
        } else if (id == R.id.btn_steam) {
            currentFunction = TTLInductionCookerProtocolUtil.FUNCTION_STEAM;
            binding.tvCurrentFunction.setText("当前功能: 蒸煮");
            sendFunctionCommand(TTLInductionCookerProtocolUtil.FUNCTION_STEAM);
        }

        // 火力选择
        else if (id == R.id.btn_high_fire) {
            currentFire = TTLInductionCookerProtocolUtil.FIRE_HIGH;
            binding.tvCurrentFire.setText("当前火力: 武火");
            sendFunctionCommand(TTLInductionCookerProtocolUtil.FIRE_HIGH);
        } else if (id == R.id.btn_low_fire) {
            currentFire = TTLInductionCookerProtocolUtil.FIRE_LOW;
            binding.tvCurrentFire.setText("当前火力: 文火");
            sendFunctionCommand(TTLInductionCookerProtocolUtil.FIRE_LOW);
        }

        // 功率调节
        else if (id == R.id.btn_plus) {
            if (currentPower < 10) {
                currentPower++;
                binding. tvCurrentPower.setText("当前功率: " + currentPower + "/10");
                sendControlCommand(TTLInductionCookerProtocolUtil.CONTROL_PLUS);
            }
        } else if (id == R.id.btn_minus) {
            if (currentPower > 1) {
                currentPower--;
                binding.tvCurrentPower.setText("当前功率: " + currentPower + "/10");
                sendControlCommand(TTLInductionCookerProtocolUtil.CONTROL_MINUS);
            }
        }

        // 定时功能
        else if (id == R.id.btn_timer) {
            Toast.makeText(this, "定时功能已触发", Toast.LENGTH_SHORT).show();
            sendControlCommand(TTLInductionCookerProtocolUtil.CONTROL_TIMER);
        }

        // 启动/停止
        else if (id == R.id.btn_start_stop) {
            isRunning = !isRunning;
            if (isRunning) {
                binding.btnStartStop.setText("停止");
                binding.btnStartStop.setBackgroundTintList(getResources().getColorStateList(android.R.color.holo_orange_dark));
                binding.tvCurrentStatus.setText("运行状态: 运行中");
                sendControlCommand(TTLInductionCookerProtocolUtil.CONTROL_START);
            } else {
                binding.btnStartStop.setText("启动");
                binding.btnStartStop.setBackgroundTintList(getResources().getColorStateList(android.R.color.holo_red_dark));
                binding.tvCurrentStatus.setText("运行状态: 已停止");
                sendControlCommand(TTLInductionCookerProtocolUtil.CONTROL_STOP);
            }
        }

        // 重新连接
        else if (id == R.id.btn_reconnect) {
//            if (serialManager != null) {
//                serialManager.closeSerialPort();
//            }
//            boolean isConnected = serialManager.openSerialPort();
//            updateConnectionStatus(isConnected);
        }
    }

    @Override
    public void setListener() {
        // 设置点击事件
        binding.btnCook.setOnClickListener(this);
        binding.btnSoup.setOnClickListener(this);
        binding.btnHotpot.setOnClickListener(this);
        binding.btnPorridge.setOnClickListener(this);
        binding.btnBoil.setOnClickListener(this);
        binding.btnSteam.setOnClickListener(this);
        binding.btnHighFire.setOnClickListener(this);
        binding. btnLowFire.setOnClickListener(this);
        binding.btnPlus.setOnClickListener(this);
        binding.btnMinus.setOnClickListener(this);
        binding.btnTimer.setOnClickListener(this);
        binding.btnStartStop.setOnClickListener(this);
        binding.btnReconnect.setOnClickListener(this);
    }

    @Override
    public void initView() {

        // 串口选择逻辑
        binding.btOpen.setOnClickListener(v -> {
            String input = binding.etAdd.getText().toString().trim();
            String path = "/dev/ttyS0"; // 默认路径

            if (!TextUtils.isEmpty(input)) {
                switch (input) {
                    case "0": path = "/dev/ttyS0"; break;
                    case "1": path = "/dev/ttyS1"; break;
                    case "2": path = "/dev/ttyS2"; break;
                    case "3": path = "/dev/ttyS3"; break;
                    case "4": path = "/dev/ttyS4"; break;
                    case "5": path = "/dev/ttyS5"; break;
                    case "6": path = "/dev/ttyS6"; break;
                    case "7": path = "/dev/ttyS7"; break;
                }
            }
            initSerial(path);
        });

        binding.btClase.setOnClickListener(v->{onDestroy();});

        binding.ivMessage.setOnClickListener(v->{finish();});
    }

    @Override
    protected ActivityCookerSlaveBinding getViewBinding() {
        return ActivityCookerSlaveBinding.inflate(LayoutInflater.from(this));
    }

    /**
     * 初始化串口
     */
    private void initSerial(String path) {
        serialManager = new SerialPortManager();
        serialManager.setOnDataReceivedListener(data -> {
            // 接收主机数据
            String hexData = TTLInductionCookerProtocolUtil.bytesToHex(data);
            mainHandler.post(() -> binding.tvHostData.setText("接收: " + hexData));

            // 解析并更新状态
            if (TTLInductionCookerProtocolUtil.verifyFrame(data)) {
                updateStatusFromFrame(data);
            }
        });

        // 尝试打开串口
        boolean isConnected = serialManager.openSerialPort(path);
        updateConnectionStatus(isConnected);
    }

    /**
     * 更新连接状态
     */
    private void updateConnectionStatus(boolean isConnected) {
        if (isConnected) {
            binding.tvConnectionStatus.setText("连接状态: 已连接");
            binding.tvConnectionStatus.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
        } else {
            binding.tvConnectionStatus.setText("连接状态: 未连接");
            binding.tvConnectionStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        }
    }

    /**
     * 从接收帧更新状态
     */
    private void updateStatusFromFrame(byte[] frame) {
        byte function = TTLInductionCookerProtocolUtil.parseFunctionCode(frame);
        int power = TTLInductionCookerProtocolUtil.parsePower(frame);

        mainHandler.post(() -> {
            if (function != TTLInductionCookerProtocolUtil.FUNCTION_NONE) {
                currentFunction = function;
                binding.tvCurrentFunction.setText("当前功能: " + TTLInductionCookerProtocolUtil.functionToText(function));
            }
            if (power > 0) {
                currentPower = power;
                binding.tvCurrentPower.setText("当前功率: " + currentPower + "/10");
            }
        });
    }

    /**
     * 发送功能指令
     */
    private void sendFunctionCommand(byte function) {
        if (serialManager == null) return;

        byte[] frame = TTLInductionCookerProtocolUtil.generateFunctionFrame(function, currentPower);
        serialManager.sendDataWithGuide(frame);
        binding.tvSlaveData.setText("发送: " + TTLInductionCookerProtocolUtil.bytesToHex(frame));
    }

    /**
     * 发送控制指令
     */
    private void sendControlCommand(byte control) {
        if (serialManager == null) return;

        byte[] frame = TTLInductionCookerProtocolUtil.generateControlFrame(control);
        serialManager.sendDataWithGuide(frame);
        binding.tvSlaveData.setText("发送: " + TTLInductionCookerProtocolUtil.bytesToHex(frame));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (serialManager != null) {
            serialManager.closeSerialPort();
        }
    }
}